﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CommonUtils
{
    public class DateUtils
    {
        /// <summary>
        /// 13位时间戳timestamp
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static long ToTimestamp(DateTime? time = null)
        {
            var dt = time ?? DateTime.Now;
            var ts = dt - DateTime.Parse("1970-01-01 08:00:00");
            return (long)ts.TotalMilliseconds;
        }
        /// <summary>
        /// 10位时间戳timestamp
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static long ToTimestamp10(DateTime? time = null)
        {
            var dt = time ?? DateTime.Now;
            var ts = dt - DateTime.Parse("1970-01-01 08:00:00");
            return (long)ts.TotalSeconds;
        }
        /// <summary>
        /// 10位时间戳
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public static DateTime FromTimestamp10(long timestamp)
        {
            DateTime start = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            return start.AddTicks(timestamp * 10000000);
        }
        /// <summary>
        /// 13位时间戳
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public static DateTime FromTimestamp(long timestamp)
        {
            DateTime start = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            return start.AddTicks(timestamp * 10000);
        }
        /// <summary>
        /// 日期转时间
        /// </summary>
        /// <param name="time"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static DateTime? ToDateTime(string time, string format)
        {
            if (string.IsNullOrWhiteSpace(time) || time == "0")
            {
                return null;
            }

            return DateTime.ParseExact(time, format, System.Globalization.CultureInfo.CurrentCulture);
        }
    }
}
